//
//  129. 求根节点到叶节点数字之和.swift
//  Top600
//
//  Created by rjb on 2021/7/29.
//

import Foundation
class Solution129 {
    func sumNumbers(_ root: TreeNode?) -> Int {
        return preOrder(root,preSum: 0)
    }
    func preOrder(_ node: TreeNode?, preSum: Int) -> Int{
        guard let node = node else {
            return 0
        }
        let sum = preSum * 10 + node.val
        if node.left == nil && node.right == nil {
            return sum
        }
       return preOrder(node.left, preSum: sum) + preOrder(node.right, preSum: sum)
    }
    
    
    static func test() {
        let solution = Solution129()
        let node4 = TreeNode(4)
        let node9 = TreeNode(9)
        let node0 = TreeNode(0)
        let node5 = TreeNode(5)
        let node1 = TreeNode(1)
        
        node4.left = node9
        node9.left = node5
        node9.right = node1
        node4.right = node0
        
        let result =  solution.sumNumbers(node4)
        print(result)
    }
}
